import Catorgeries from "@/components/Catorgeries";
import FloatBack from "@/components/FloatBack";
import { useEffect, useState } from "react";
import { getNewsList } from "@/api";
import { formatArticleContent } from "@/utils/formatArticleContent";

import { INews } from "@/types";
import VirtalList from "@/components/VirtalList";
const List = () => {
    const [newsList, setNewsList] = useState<INews[]>([]);
    const pageSize = 10;
    const [pageNum, setPageNum] = useState<number>(1);
    useEffect(() => {
        getNewsList({ pageNum, pageSize }).then((res: any) => {
            const new_news_list = res.data[0].contents.map((i: any) => {
                return {
                    id: i.id,
                    title: i.title,
                    date: i.published_at,
                    author: i.article.editor,
                    imageUrl: i.article.thumbnail,
                    content: formatArticleContent(
                        i.article.origin,
                        i.article.thumbnail,
                        true
                    ),
                };
            });
            if (pageNum <= 1) {
                setNewsList(new_news_list);
            } else {
                setNewsList(newsList.concat(new_news_list));
            }
        });
    }, [pageNum]);
    const debounceFn = (fn: Function, wait: number) => {
        let time: any;
        let context = this;
        return (...args: any[]) => {
            if (time) {
                clearTimeout(time);
                time = null;
            }
            time = setTimeout(() => {
                fn.apply(context, args);
            }, wait);
        };
    };
    const debounceSetPageNum = debounceFn(setPageNum, 500);
    return (
        <div className="h-dvh overflow-auto box-border flex flex-col">
            <div className="sticky top-0 z-10 -mt-5 bg-white shrink-0">
                <Catorgeries round={false} light={true} hideAdd={true} />
            </div>
            <VirtalList
                className={"grow-1 overflow-hidden overflow-y-auto"}
                data={newsList}
                onLoad={() => debounceSetPageNum(pageNum + 1)}
            />
            <FloatBack />
        </div>
    );
};

export default List;
